from .models import Customer
from rest_framework import serializers
import re


"""
1. version 路径参数添加注释
2. 查询字段 添加注释
3. 删除方法 不需要更改查询字段
4. 更新方法  添加字段

# restf 功能大全：https://www.cnblogs.com/victorwu/p/7418368.html
"""


class CustomerSerializer(serializers.ModelSerializer):
    """
    序列化客户信息
    """

    joined_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    # address_code = serializers.CharField()

    class Meta:
        model = Customer
        fields = "__all__"

        read_only_fields = ("id", "joined_time", "update_time")  # 只读字段

        extra_kwargs = {
            'name': {
                'help_text': '客户名，字符串，必填，最大20个字符，最小2个字符',
                'label': Customer._meta.get_field("name").verbose_name,
                'required': True,
                'min_length': 2,
                'max_length': 20,
                'error_messages': {
                    'min_length': '最少2个字符',
                    'max_length': '最多20个字符',
                    'required': '请输入客户名',
                    "blank": "请输入客户名",
                }
            },
            'nickname': {
                'help_text': '称呼，可选，最大20个字符，最小2个字符',
                'label': Customer._meta.get_field("nickname").verbose_name,
                'min_length': 2,
                'max_length': 20,
                'allow_null': True,
                'allow_blank': True,
                'error_messages': {
                    'min_length': '最少2个字符',
                    'max_length': '最多20个字符'
                }
            },
            'telephone': {
                'help_text': '手机号，字符串，可选',
                'label': Customer._meta.get_field("telephone").verbose_name,
                'allow_null': True,
                'allow_blank': True,
            },
        }

    # 验证手机号
    def validate_telephone(self, telephone):
        if not telephone: return telephone
        if len(telephone) != 11 or not telephone.isdigit():
            raise serializers.ValidationError("请输入正确手机号")

        REGEX_TELEPHONE = r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$'

        if not re.match(REGEX_TELEPHONE, telephone):
            raise serializers.ValidationError("请输入正确手机号")

        return telephone

    # 自定义字段返回格式
    def to_representation(self, instance):
        representation = super(CustomerSerializer, self).to_representation(instance)
        representation['grade_label'] = instance.grade + "(" + instance.get_grade_display() + ")"
        representation['platform_label'] = instance.get_platform_display()
        representation['address_code'] = instance.get_address_code()
        return representation
